package wh.自除数;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2022/3/24 14:23
 * @description:自除数 是指可以被它包含的每一位数整除的数
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        List<Integer> integers = selfDividingNumbers(1, 22);
        System.out.println(integers);

    }

    //解法1 不推荐，双重for循环加上字符转换，太麻烦.可以看看勋哥代码
    public  static List<Integer> selfDividingNumbers(int left, int right) {
        List<Integer> myList = new ArrayList<>();
        for (int i = left; i <= right; i++) {
            String s = Integer.toString(i);
            char[] chars = s.toCharArray();
            for (int j = 0; j < chars.length; j++) {
                char aChar = chars[j];
                int n = Integer.parseInt(String.valueOf(aChar));
                if(n == 0){
                    break;
                }
                if(i % n != 0){
                    break;
                }
                if(j == chars.length - 1){
                    int num = Integer.parseInt(String.valueOf(chars));
                    myList.add(num);
                }
            }
        }
        return myList;
    }


    //方法2  官方解法
    public static List<Integer> selfDividingNumbers2(int left, int right) {
            List<Integer> ans = new ArrayList();
            for (int n = left; n <= right; ++n) {
                if (selfDividing(n)) ans.add(n);
            }
            return ans;
        }
        public  static boolean selfDividing(int n) {
            for (char c: String.valueOf(n).toCharArray()) {
                //通过c - '0' 可以很巧妙的把char类型字符，转换为int型
                if (c == '0' || (n % (c - '0') > 0))
                    return false;
            }
            return true;
        }



}
